<template>
  <Modal v-model="show" title="设备检测" @on-cancel="oncancel" @on-ok="onok">
    <Steps v-if="tab !== 0" :current="currentStep">
      <Step title="摄像头"></Step>
      <Step title="声音"></Step>
      <Step title="麦克风"></Step>
      <Step title="网络"></Step>
    </Steps>
    <div v-show="tab === 0" class="dtm-page1">
      <h5 class="text-center">设备连接</h5>
      <p class="text-center">
        设备检测前请务必给当前页面开放摄像头，麦克风权限哦~
      </p>
      <div class="device-list">
        <div class="device-item">
          <span>摄像头</span>
          <span v-if="!reStartTesting">
            {{ hasCameraConnect ? "√" : "x" }}
          </span>
        </div>
        <div class="device-item">
          <span>扬声器</span>
          <span v-if="!reStartTesting">
            {{ hasVoiceConnect ? "√" : "x" }}
          </span>
        </div>
        <div class="device-item">
          <span>麦克风</span>
          <span v-if="!reStartTesting">
            {{ hasMicConnect ? "√" : "x" }}
          </span>
        </div>
        <div class="device-item">
          <span>网络</span>
          <span v-if="!reStartTesting">
            {{ hasNetworkConnect ? "√" : "x" }}
          </span>
        </div>
      </div>
      <Progress
        v-if="isReload && reStartTesting"
        :percent="percent"
        hide-info
      />

      <p v-if="reStartTesting" class="device-status-label">
        设备正在连接中
      </p>

      <div class="text-center" v-if="connectResult">
        <p v-if="hasResult" class="device-status-label">
          设备及网络连接成功，请开始设备检测
        </p>
        <Button
          :disabled="reStartTesting"
          type="primary"
          @click.stop.prevent="nextpage"
          >开始检测</Button
        >
      </div>
      <template v-if="!connectResult && hasResult">
        <p class="device-status-label">
          {{ deviceConnectInfo.connectInfo }}
        </p>
      </template>
      <div v-if="!connectResult" class="text-center">
        <Button
          :disabled="reStartTesting"
          type="primary"
          @click.stop.prevent="reStartLink"
          >重新连接</Button
        >
      </div>
    </div>
    <div v-show="tab === 1" class="dtm-page2">
      <Select v-model="cameraId" style="width:200px" @change="changeCamera">
        <Option
          v-for="item in cameraList"
          :value="item.deviceId"
          :key="item.deviceId"
          >{{ item.label }}</Option
        >
      </Select>
      <div id="camera-video"></div>
    </div>
  </Modal>
</template>

<script>
import TRTC from "trtc-js-sdk";
export default {
  name: "DeviceTestModal",
  props: {
    visiable: {
      type: Boolean,
      default: false
    }
  },
  inject: ["live"],
  data() {
    return {
      show: false,
      percent: 0,
      timer: null,
      isReload: true,
      tab: 0,
      currentStep: 0,
      cameraId: "",
      micPhoneId: ""
    };
  },

  computed: {
    connectResult({ live }) {
      return live.liveDeviceUtils.connectResult;
    },

    deviceConnectInfo({ live }) {
      return live.liveDeviceUtils.deviceConnectInfo;
    },
    reStartTesting({ live }) {
      return live.liveDeviceUtils.reStartTesting;
    },
    hasCameraConnect({ live }) {
      return live.liveDeviceUtils.hasCameraConnect;
    },

    hasMicConnect({ live }) {
      return live.liveDeviceUtils.hasMicConnect;
    },

    hasVoiceConnect({ live }) {
      return live.liveDeviceUtils.hasVoiceConnect;
    },

    hasNetworkConnect({ live }) {
      return live.liveDeviceUtils.hasNetworkConnect;
    },
    hasResult({ live }) {
      return live.liveDeviceUtils.hasResult;
    },
    cameraList({ live }) {
      return live.liveDeviceUtils.cameraList;
    },

    micPhoneList({ live }) {
      return live.liveDeviceUtils.micPhoneList;
    }
  },

  watch: {
    visiable: {
      handler(value) {
        this.show = value;
        if (value) {
          //重新开始检测
          this.reStartLink();
        }
      },
      immediate: true
    }
  },

  methods: {
    oncancel() {
      this.currentStep = 0;
      this.tab = 0;
      this.timer && clearInterval(this.timer);
      this.finishDeviceTesting();
      this.$emit("update:visiable", false);
    },
    onok() {
      this.$emit("update:visiable", false);
    },
    reStartLink() {
      this.isReload = false;
      this.percent = 0;
      this.$nextTick(() => {
        this.isReload = true;
      });
      this.live.liveDeviceUtils.startDeviceConnect();

      this.timer = setInterval(() => {
        this.percent = this.percent + 10;
        if (this.percent >= 100) {
          clearInterval(this.timer);
        }
      }, 100);
    },
    async nextpage() {
      this.tab++;
      if (this.tab === 1) {
        this.cameraId = this.cameraList[0].deviceId;
        console.log(this.cameraId);
        // 创建本地视频流
        await this.createLocalStream(
          {
            audio: false,
            video: true,
            cameraId: this.cameraId
          },
          "camera-video"
        );
      }
      if (this.tab === 2) {
        // this.micPhoneId = this.micPhone.deviceId;
      }
    },
    changeCamera() {},
    /**
     * 抽离createStream的公共处理函数
     */
    async createLocalStream(constraints, container) {
      this.localStream = TRTC.createStream(constraints);
      try {
        await this.localStream.initialize();
      } catch (error) {
        this.live.liveDeviceUtils.handleGetUserMediaError(error);
      }
      container && this.localStream.play(container);
    },

    finishDeviceTesting() {
      // 停止摄像头/麦克风的流采集并释放摄像头/麦克风设备
      this.localStream && this.localStream.close();
      // client && client.leave();
      // client && client.off('network-quality');
      // // 停止播放器的音乐
      // let audioPlayer = document.querySelector('#audio-player');
      // if (!audioPlayer.paused) {
      //   audioPlayer.pause();
      // }
      // audioPlayer.currentTime = 0;
    }
  },
  created() {}
};
</script>

<style lang="scss">
.text-center {
  text-align: center;
  font-size: 18px;
}
.dtm-page1 {
  .device-list {
    display: flex;
    width: 80%;
    margin: 0 auto;
    height: 40px;
    text-align: center;
    justify-content: space-around;
    align-items: center;
  }
  .device-status-label {
    font-size: 16px;
    text-align: center;
  }
}
</style>
